//
//  YYAuthSDK.m
//  UserAuthoTest
//
//  Created by Cloud on 2018/9/14.
//  Copyright © 2018年 崔昌云. All rights reserved.
//

#import "YYSocialSDK.h"
#import "YYSocialConst.h"
#import "YYSocialResponse.h"
#import "NSString+YYSocialSDK.h"
#import "NSDictionary+YYSocialSDK.h"


@interface YYSocialSDK()
@property (nonatomic, copy) YYSocialRequestCompletionHandler completedBlock;
///调用越狱社交分享
@property (nonatomic, copy) YYSocialRequestCompletionHandler shareCompletedBlock;
///获取用户信息
@property (nonatomic, copy) YYSocialRequestCompletionHandler authCompletedBlock;

///社会化动作
@property (nonatomic, copy) YYSocialConfigCompletionHandler socialActionBlock;

@property (nonatomic, copy) NSString *yyAppid;
///来自其它app的社交信息
@property (nonatomic, copy) NSDictionary *socialParams;
///需要告知其它app的分享结果
@property (nonatomic, copy) NSDictionary *shareResult;
@end

@implementation YYSocialSDK

+(instancetype)defaultManager{
    static dispatch_once_t onceToken;
    static YYSocialSDK *instance;
    dispatch_once(&onceToken, ^{
        instance = [[YYSocialSDK alloc] init];
    });
    return instance;
}

+(BOOL)isYYAppInstalled{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:YYA_WxUrlPrefix]];
}
/**
 *  配置社会化功能（授权登录、分享）
 
 *  @param completion   回调
 */
- (void)configSocialFuncCompletion:(YYSocialConfigCompletionHandler)completion{
  self.socialActionBlock = [completion copy];
}

/**
 *  授权并获取用户信息
 
 *  @param URLScheme URLScheme
 *  @param completion   回调
 */
- (void)getUserInfoWith:(NSString *)URLScheme
             Completion:(YYSocialRequestCompletionHandler)completion{
    if(completion){
        self.completedBlock = [completion copy];
    }
    if(![self.class isYYAppInstalled]){
        YYSocialKitLog(@"未安装越越社交");
        return;
    }
    NSDictionary *dict = @{@"fromAppUrlScheme":URLScheme,@"requestType":YYA_YYReruestTypeAuth,@"dataString":@{}};
    NSString *jsonStr = dict.yy_jsonString.yy_ReplaceEmptyString.yy_URLEncodedString;
    NSString * openUrl = [NSString stringWithFormat:@"%@%@",YYA_YyUrlClient,jsonStr];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:^(BOOL success) {
    }];
}
/**
 *  分享到越越社交
 
 *  @param messageObject 分享消息体
 *  @param URLScheme URLScheme
 *  @param completion   回调
 */
- (void)shareToYueYue:(YYSocialMessageObject *)messageObject
            URLScheme:(NSString *)URLScheme
           Completion:(YYSocialRequestCompletionHandler)completion{
    if(completion){
        self.completedBlock = [completion copy];
    }
    if(![self.class isYYAppInstalled]){
        YYSocialKitLog(@"未安装越越社交");
        return;
    }
    NSMutableDictionary *shareInfo = @{}.mutableCopy;
    shareInfo[@"title"] = messageObject.title;
    shareInfo[@"describe"] = messageObject.descr;
    shareInfo[@"image"] = messageObject.imageUrl;
    shareInfo[@"linkUrl"] = messageObject.linkUrl;
  
    NSDictionary *dict = @{@"fromAppUrlScheme":URLScheme,@"requestType":YYA_YYReruestTypeShare,@"dataString":shareInfo};
    NSString *jsonStr = dict.yy_jsonString.yy_ReplaceEmptyString.yy_URLEncodedString;
    NSString * openUrl = [NSString stringWithFormat:@"%@%@",YYA_YyUrlClient,jsonStr];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:^(BOOL success) {
        
    }];
}
/**
 
 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用
 @param url 支付结果Url
 @return 成功返回YES，失败返回NO
 */
-(BOOL)handleOpenURL:(NSURL *)url{
    
    NSString *urlString = url.absoluteString.yy_URLDecodedString;
    NSDictionary *paramsStr = [NSString getParamsWithUrlString:urlString];
    NSDictionary *params = paramsStr;
    self.socialParams = params;
    if ([params[@"responseType"] isEqualToString:YYA_YYResponseTypeAuth]) {
      NSDictionary *result = paramsStr[@"dataString"];
      if ([result[@"code"] isEqualToString:@"0"]) {
        if(self.completedBlock) self.completedBlock([self userInfoResponseWithResultInfo:result[@"result"]],nil);
      }else if ([result[@"code"] isEqualToString:@"1"]||[result[@"code"] isEqualToString:@"2"]) {
        NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:-1 userInfo:@{@"message":result[@"result"]}];
        if(self.completedBlock) self.completedBlock(nil,error);
      }
        return YES;
    }else if ([params[@"responseType"] isEqualToString:YYA_YYResponseTypeShare]){
        NSDictionary *result = paramsStr[@"dataString"];
        if ([result[@"code"] isEqualToString:@"100"]) {
            if(self.completedBlock) self.completedBlock(result[@"result"],nil);
        }else if ([result[@"code"] isEqualToString:@"101"]||[result[@"code"] isEqualToString:@"102"]) {
            NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:-1 userInfo:@{@"message":result[@"result"]}];
            if(self.completedBlock) self.completedBlock(nil,error);
        }
        return YES;
    }
    
    
    return NO;
}

/**
 *  其他应用打开APP获取用户信息
 
 *  @param url 传进的参数URL
 */
- (void)applicationOpenURL:(NSURL *)url{
  NSString *urlString = url.absoluteString.yy_URLDecodedString;
  NSDictionary *params = [NSString getParamsWithUrlString:urlString];
  self.socialParams = params;
  if ([self.socialParams[@"requestType"] isEqualToString:YYA_YYReruestTypeAuth]) {
    !self.socialActionBlock?:self.socialActionBlock(YYA_YYAuthComponentName);
  }else if ([self.socialParams[@"requestType"] isEqualToString:YYA_YYReruestTypeShare]){
    !self.socialActionBlock?:self.socialActionBlock(YYA_YYShareComponentName);
  }
}

/**
 *  响应分享
 
 */
- (void)responseShareWithResult:(id)result code:(NSString *)code{
    NSMutableDictionary *temp = @{}.mutableCopy;
    temp[@"result"] = result;
    temp[@"code"] = code;
    self.shareResult = temp.copy;
}
/**
 *  响应分享结束后返回其它APP
 
 */
- (void)responseShareGoBackApp{
   [self responseSocial:YYA_YYResponseTypeShare responseInfo:self.shareResult];
    self.shareResult = nil;
}
/**
 *  响应获取用户信息
 
 *  @param authInfo   用户信息
 */
- (void)responseAuthWithAuthInfo:(id)authInfo code:(NSString *)code{
    NSMutableDictionary *temp = @{}.mutableCopy;
    temp[@"result"] = authInfo;
    temp[@"code"] = code;
    [self responseSocial:YYA_YYResponseTypeAuth responseInfo:temp.copy];
}

- (void)responseSocial:(NSString *)responseType responseInfo:(NSDictionary *)responseInfo{
    responseInfo = responseInfo?responseInfo:@{};
    NSString *fromAppUrlScheme = self.socialParams[@"fromAppUrlScheme"];
    if (!fromAppUrlScheme) {YYSocialKitLog(@"缺少 fromAppUrlScheme！") return;}
    NSDictionary *dict = @{@"fromAppUrlScheme":YYA_YYUrlSign,@"responseType":responseType,@"dataString":responseInfo};
    NSString *jsonStr = dict.yy_jsonString.yy_ReplaceEmptyString.yy_URLEncodedString;
    NSString * openUrl = [NSString stringWithFormat:@"%@%@",YYA_YyClientConfig(fromAppUrlScheme),jsonStr];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:^(BOOL success) {
            
        }];
    });
}
- (NSDictionary *)socialInfoParams{
  return self.socialParams[@"dataString"];
}
- (YYSocialUserInfoResponse *)userInfoResponseWithResultInfo:(NSDictionary*)resultInfo{
  YYSocialUserInfoResponse *response = [YYSocialUserInfoResponse new];
  response.token = resultInfo[@"yx_token"];
  response.nickname = resultInfo[@"nickname"];
  response.uid = resultInfo[@"user_id"];
  response.username = resultInfo[@"username"];
  response.sex = resultInfo[@"sex"];
  response.headimgurl = resultInfo[@"headimgurl"];
  return response;
}
@end
